﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Besture.Bll;
using Besture.Common;
using Besture.Common.Definition;
using Besture.Common.Helper;
using Besture.Model;
using Besture.UI.ClassHelper;
using DevExpress.Web.ASPxGridView;
using DevExpress.Web.Data;

namespace Besture.UI.Admin.Sys
{
    public partial class SqlDbBak : BasePage
    {
        #region 页面加载事件

        /// <summary>
        /// 页面加载
        /// </summary>
        protected override void InitialLoad()
        {
            //初始化备份名称
            txtDbName.Text = string.Format("{0}_{1}.bak", GetDbName(), DateTimeHelper.GetTimestamp());

            BindData();

            AspxGridViewHelper.InitAspxGridView(grid);
        }

        /// <summary>
        /// 回发
        /// </summary>
        protected override void PostBackLoad()
        {

        }

        #endregion

        /// <summary>
        /// 绑定数据
        /// </summary>
        public void BindData()
        {
            DataBaseBackUpDac dac = new DataBaseBackUpDac();
            grid.DataSource = dac.GetDataTable();
            grid.DataBind();
        }


        /// <summary>
        /// AspxGridView回发事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grid_CustomCallback(object sender, ASPxGridViewCustomCallbackEventArgs e)
        {
            if (e.Parameters == "Refresh")
                grid.DataBind();
        }


        /// <summary>
        /// 删除单条数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grid_RowDeleting(object sender, ASPxDataDeletingEventArgs e)
        {
            e.Cancel = true;
            int ID = Convert.ToInt32(e.Keys[0]);

            DataBaseBackUpDac dac = new DataBaseBackUpDac();
            DataBaseBackUpModel model = dac.GetModel(ID);
            //删除文件
            string path =  "~//Upload//DataBaseBak//" + model.Name;
            IoHelper.DeleteFile(path);
            dac.Delete(ID);
            BindData();
        }


        protected void btnSubmit_Click(object obj, EventArgs eventArgs)
        {
            string bakName = txtDbName.Text;
            if(!bakName.EndsWith(".bak"))
            {
                bakName += ".bak";
            }
            //获取数据库名称
            string dataName = GetDbName();
            if(string.IsNullOrEmpty(dataName))
            {
                PageAlert("连接字符串异常，请联系管理员！");
                return;
            }

            try
            {
                string path = Server.MapPath("~//Upload//DataBaseBak//") + bakName;

                //判断备份数据库文件是否存在
                if (System.IO.File.Exists(path))
                {
                    PageAlert("此备份名称已经存在，请修改！");
                    return;
                }

                

                SqlConnection connection = new SqlConnection(AppSettings.ConnectionString);
                SqlCommand command = new SqlCommand("use master;backup database @name to disk=@path;", connection);
                connection.Open();
                
                command.Parameters.AddWithValue("@name", dataName);
                command.Parameters.AddWithValue("@path", path);
                command.ExecuteNonQuery();
                connection.Close();

                //备份成功 插入数据库
                DataBaseBackUpModel model = new DataBaseBackUpModel();
                model.Name = bakName;
                model.FileSize = IoHelper.GetFileSize("~//Upload//DataBaseBak//" + bakName);
                model.CreateBy = AdminUserService.AdminLoginUser.ID;

                DataBaseBackUpDac dac = new DataBaseBackUpDac();
                dac.Add(model);
                PageAlert("备份成功，备份名称为【" + bakName + "】！");
            }
            catch (Exception exception)
            {
                PageAlert("备份出错，请联系管理员！");
                throw;
            }
            finally
            {
                //绑定数据
                BindData();
            }
        }

        /// <summary>
        /// 获取数据库名称
        /// </summary>
        /// <returns></returns>
        protected string GetDbName()
        {
            string dbName = string.Empty;
            //Data Source=;uid=sa;pwd=123;database=CmsInit;timeout=120
            string[] args = StringHelper.SplitString(AppSettings.ConnectionString, ';');
            for (int i = 0; i < args.Count(); i++)
            {
                if(args[i].ToLower().StartsWith("database"))
                {
                    dbName = args[i].Replace("database=","");
                    break;
                }
            }
            return dbName;
        }
    }
}